﻿/************************************************************************************************************************
* 命名空间: DocumentTool.Strategy
* 项目描述:
* 版本名称: v1.0.0.0
* 作　　者: 唐晓军
* 所在区域: 北京
* 机器名称: DESKTOP-F6QRRBM
* 注册组织: 学科网（www.zxxk.com）
* 项目名称: 学易作业系统
* CLR版本:  4.0.30319.42000
* 创建时间: 2017/9/30 10:38:46
* 更新时间: 2017/9/30 10:38:46
* 
* 功 能： N/A
* 类 名： OfficeComponent
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────────────────────────────
* V0.01 2017/9/30 10:38:46 唐晓军 初版
*
* Copyright (c) 2017 Lir Corporation. All rights reserved.
*┌──────────────────────────────────────────────────────────┐
*│　此技术信息为本公司机密信息，未经本公司书面同意禁止向第三方披露．                                                  │
*│　版权所有：北京凤凰学易科技有限公司　　　　　　　　　　　　　                                                      │
*└──────────────────────────────────────────────────────────┘
************************************************************************************************************************/

using Microsoft.Office.Core;
using System;
using System.Reflection;
using QWord = Microsoft.Office.Interop.Word;

namespace DocumentTool
{
    public class OfficeComponent : IDocStrategy
    {
        public void WordToHtml(string inputPath, string outputPath)
        {
            throw new NotImplementedException();
        }
        public void WordToPdf(string inputPath, string outputPath)
        {
            try
            {

                Convert(inputPath, outputPath, QWord.WdSaveFormat.wdFormatPDF);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Convert(string input, string output, QWord.WdSaveFormat format)
        {
            // Create an instance of Word.exe
            QWord.Application oWord = new QWord.Application();
            QWord.Document oDoc = null;
            // Make this instance of word invisible (Can still see it in the taskmgr).
            try
            {
                oWord.Visible = false;
                // Interop requires objects.
                object oMissing = Missing.Value;
                object isVisible = true;
                object readOnly = true;
                object oInput = input;
                object oOutput = output;
                object oFormat = format;

                // Load a document into our instance of word.exe
                oDoc = oWord.Documents.Open(ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                // Make this document the active document.
                oDoc.Activate();
                // Save this document in Word 2003 format.
                oDoc.SaveAs(ref oOutput, ref oFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                // Always close Word.exe.
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
            catch (Exception ex)
            {
                Close(oDoc, oWord);
                throw ex;
            }
        }

        #region 关闭文档
        /// <summary>   
        /// 关闭文档   
        /// </summary>   
        /// <param name="wDoc">Document对象</param>   
        /// <param name="WApp">Application对象</param>  
        public static void Close(QWord.Document wDoc, QWord.Application WApp)
        {
            // 指定文档的保存操作。可以是下列 WdSaveOptions 值之一：wdDoNotSaveChanges、wdPromptToSaveChanges 或 wdSaveChanges
            Object SaveChanges = QWord.WdSaveOptions.wdSaveChanges;
            // 指定文档的保存格式。可以是下列 WdOriginalFormat 值之一：wdOriginalDocumentFormat、wdPromptUser 或 wdWordDocument。   
            Object OriginalFormat = QWord.WdOriginalFormat.wdOriginalDocumentFormat;
            // 如果为 true，则将文档传送给下一个收件人。如果没有为文档附加传送名单，则忽略此参数。
            Object RouteDocument = false;
            try
            {
                if (wDoc != null)
                    wDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
                if (WApp != null)
                    WApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        private void WordToPdfBackup(string inputPath, string outputPath)
        {
            //QWord.Application lobjWordApp = null;
            //QWord.Document objDoc = null;
            object missing = Missing.Value;
            //object lobjSaveChanges = null;

            QWord.Application wordApp = new QWord.Application();
            QWord.Document wordDoc = null;

            try
            {
                object fileName = inputPath;
                object savePath = outputPath;
                object saveFormat = QWord.WdSaveFormat.wdFormatPDF;
                object saveEncoding = MsoEncoding.msoEncodingUTF8;
                wordApp.Visible = true;
                wordApp.DisplayRecentFiles = false;
                wordApp.DisplayAlerts = QWord.WdAlertLevel.wdAlertsNone;


                wordDoc = wordApp.Documents.Open(fileName, missing, missing, missing, missing, missing, missing, missing, missing,
                        QWord.WdSaveFormat.wdFormatXMLDocument, missing, true, missing, missing, true, missing);


                //QWord.Document doc = wordApp.Documents.Open(ref fileName,
                //    ref missing, ref readOnly, ref missing, ref missing, ref missing,
                //    ref missing, ref missing, ref missing, ref missing, ref missing,
                //    ref isVisible, ref openAndRepair, ref missing, ref missing, ref missing);
                //doc.WebOptions.AllowPNG = true;
                //doc.WebOptions.RelyOnCSS = true;
                //doc.WebOptions.Encoding = MsoEncoding.msoEncodingUTF8;


                wordDoc.SaveAs(savePath, saveFormat);

                wordDoc.Close(ref missing, ref missing, ref missing);
                wordApp.Quit(ref missing, ref missing, ref missing);

            }
            catch (Exception ex)
            {
                //其他日志操作；  

            }
            finally
            {
                wordDoc = null;
                wordApp = null;
                //主动激活垃圾回收器，主要是避免超大批量转文档时，内存占用过多，而垃圾回收器并不是时刻都在运行！  
                //GC.Collect();
                //GC.WaitForPendingFinalizers();
            }
        }
    }
}
